package com.imooc.controller;

import com.imooc.pojo.Users;
import com.imooc.pojo.UsersVO;
import com.imooc.service.UsersService;
import com.imooc.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class SSOController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisOperator redisOperator;

    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_USER_TICKET = "redis_user_ticket";
    public static final String REDIS_TMP_TICKET = "redis_tmp_ticket";
    public static final String COOKIE_USER_TICKET = "cookie_user_ticket";

    @GetMapping("/login")
    public String login(String returnUrl,
                        Model model,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        log.info("进入SSOController.login. returnUrl={}", returnUrl);
        //设置页面属性
        model.addAttribute("returnUrl", returnUrl);

        //1. 获取userTicket门票，如果cookie中能够获取到，证明用户登录过，此时签发一个一次性的临时票据，并且回跳
        String userTicket = getCookie(request, COOKIE_USER_TICKET);

        //校验用户是否已经登录，如果登录直接回跳
        if (verifyUserTicket(userTicket)) {
            String tmpTicket = UUID.randomUUID().toString().trim();
            redisOperator.set(REDIS_TMP_TICKET + ":" + tmpTicket, MD5Utils.getMD5Str(tmpTicket), 600);
            return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
        }

        //2. 用户从未登录，进入登录页面
        return "login";
    }

    /**
     * 验证用户门票是否通过
     *
     * @param userTicket
     * @return
     */
    private boolean verifyUserTicket(String userTicket) {
        if (StringUtils.isBlank(userTicket)) {
            return false;
        }
        String userId = redisOperator.get(REDIS_USER_TICKET + ":" + userTicket);
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        //2. 验证门票对应的user会话是否存在
        String userRedis = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
        if (StringUtils.isBlank(userRedis)) {
            return false;
        }
        return true;
    }

    /**
     * CAS的统一登录接口
     * 目的：
     * 1. 登录后创建用户的全局会话  -->uniqueToke
     * 2. 创建用户的全局门票,用以表示在CAS端是否登录
     * 3. 创建用户的临时票据,用于回跳回传
     *
     * @param username
     * @param password
     * @param returnUrl
     * @param model
     * @param request
     * @param response
     * @return
     */
    @PostMapping("doLogin")
    public String doLogin(String username,
                          String password,
                          String returnUrl,
                          Model model,
                          HttpServletRequest request,
                          HttpServletResponse response) {
        log.info("进入SSOController.doLogin. username={}", username);
        //设置页面属性
        model.addAttribute("returnUrl", returnUrl);

        //1.判断用户名或密码不能为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            model.addAttribute("errmsg", "用户名或密码不能为空");
            return "login";
        }

        Users userResult = usersService.queryUserForLogin(username,
                MD5Utils.getMD5Str(password));
        if (userResult == null) {
            model.addAttribute("errmsg", "用户名或密码错误");
            return "login";
        }

        //2. 实现用户的redis会话
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);
        String uniqueToken = UUID.randomUUID().toString().trim();
        usersVO.setUserUniqueToken(uniqueToken);
        redisOperator.set(REDIS_USER_TOKEN + ":" + userResult.getId(), JsonUtils.objectToJson(usersVO));

        //3. 生成ticket门票，全局门票，代表用户在CAS端登录过
        String userTicket = UUID.randomUUID().toString().trim();
        //3.1 用户的全局门票需要方法CAS中。设置cookie
        setCasCookie(COOKIE_USER_TICKET, userTicket, response);

        //4. userTicket关联用户id，并且放入redis中，代表这个用户有门票了
        redisOperator.set(REDIS_USER_TICKET + ":" + userTicket, userResult.getId());

        //5. 生成临时门票，回跳到调用端网站，是由CAS端所签发的一个一次性临时ticket
        String tmpTicket = UUID.randomUUID().toString().trim();
        redisOperator.set(REDIS_TMP_TICKET + ":" + tmpTicket, MD5Utils.getMD5Str(tmpTicket), 600);

        /*
            userTicket: 用于表示用户在CAS端的一个登录状态，全局使用
            tmpTicket： 用于颁发给用户进行一次性验证的票据，有时效性
         */

        return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
    }

    private void setCasCookie(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        //TODO 需要修改
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 验证临时票据
     *
     * @param tmpTicket
     * @param request
     * @param response
     * @return
     */
    @PostMapping("verifyTmpTicket")
    @ResponseBody
    public IMOOCJSONResult verifyTmpTicket(String tmpTicket,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        log.info("进入SSOController.verifyTmpTicket. ");
        // 使用一次性临时票据来验证用户是否登录，如果登录，把用户的会话信息返回给站点
        // 使用完毕后，销毁临时票据

        String tmpTicketValue = redisOperator.get(REDIS_TMP_TICKET + ":" + tmpTicket);
        if (StringUtils.isBlank(tmpTicketValue)) {
            return IMOOCJSONResult.errorUserTicket("用户无临时票据");
        }
        if (!tmpTicketValue.equals(MD5Utils.getMD5Str(tmpTicket))) {
            return IMOOCJSONResult.errorUserTicket("用户临时票据异常");
        }
        //临时票据无异常，就要立即销毁
        redisOperator.del(REDIS_TMP_TICKET + ":" + tmpTicket);

        //1. 验证并且获取用户的userTicket
        String userTicket = getCookie(request, COOKIE_USER_TICKET);
        if (StringUtils.isBlank(userTicket)) {
            return IMOOCJSONResult.errorUserTicket("用户cookie获取异常");
        }
        String userId = redisOperator.get(REDIS_USER_TICKET + ":" + userTicket);
        if (StringUtils.isBlank(userId)) {
            return IMOOCJSONResult.errorUserTicket("用户票据异常");
        }
        //2. 验证门票对应的user会话是否存在
        String userRedis = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
        if (StringUtils.isBlank(userRedis)) {
            return IMOOCJSONResult.errorUserTicket("用户票据异常，用户信息为空");
        }
        //验证成功，返回ok
        return IMOOCJSONResult.ok(JsonUtils2.stringToObj(userRedis, UsersVO.class));
    }

    private String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || StringUtils.isBlank(key)) {
            return null;
        }
        List<Cookie> cookieList = Arrays.stream(cookies).filter(e -> e.getName().equals(key))
                .collect(Collectors.toList());
        return cookieList.get(0).getValue();
    }

    @PostMapping("/logout")
    @ResponseBody
    public IMOOCJSONResult logout(String userId,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {
        log.info("进入SSOController.logout. userId={}", userId);

        //1. 获取CAS中的用户门票
        String userTicket = getCookie(request, COOKIE_USER_TICKET);
        //2. 清除用户的ticket
        //2.1 删除cookie中的ticket
        deleteUserCookie(COOKIE_USER_TICKET, response);
        //2.2 删除redis中的ticket
        redisOperator.del(REDIS_USER_TICKET + ":" + userTicket);

        //3. 清除用户的全局会话
        redisOperator.del(REDIS_USER_TOKEN + ":" + userId);

        return IMOOCJSONResult.ok();
    }

    private void deleteUserCookie(String key, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, null);
        //TODO 需要修改
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

}
